<template>
  <div>
    <Header v-if="showHeader" title="我要申请"></Header>
    <div class="apply">
      <ul class="read_list">
        <li>
          <label>申请内容</label>
          <input type="text" :value="readList.apply_title" readonly />
        </li>
        <li>
          <label>当前考核时期</label>
          <input type="text" :value="readList.cycle_status_desc" readonly />
        </li>
        <li>
          <label>延期开始时间</label>
          <input type="text" :value="readList.start_time" readonly />
        </li>
        <li>
          <label>延期结束时间</label>
          <input type="text" :value="readList.end_time" readonly />
        </li>
        <li>
          <label>周期时长(天)</label>
          <input type="text" :value="readList.cycle_long" readonly />
        </li>
        <li>
          <label>历史申请(次)</label>
          <input type="text" :value="readList.history_apply_num" readonly />
        </li>
      </ul>
      <div class="apply_reason">
        <p>申请理由</p>
        <van-cell-group>
          <van-field
            type="textarea"
            rows="3"
            autosize
            v-model="applyReason"
            maxlength="255"
            show-word-limit
            placeholder="请输入延期申请理由"
          />
        </van-cell-group>
      </div>
      <div class="upload_images">
        <p>
          图片上传
          <span>(限上传3张图片)</span>
        </p>
        <van-uploader v-model="fileList" multiple :max-count="3" />
      </div>
      <ReferData :ReferDataList="ReferDataList"></ReferData>
      <ApprovalStep :stepList="stepList" :activeStep="activeStep"></ApprovalStep>
      <van-tabbar :z-index="1000">
        <van-tabbar-item>
          <van-button
            size="large"
            @click="submitApply"
            :disabled="applyReason.length<=0|| !applyReason"
          >提交</van-button>
        </van-tabbar-item>
      </van-tabbar>
    </div>
    <Loading v-show="showLoading"></Loading>
  </div>
</template>
<script>
import ReferData from "@/components/business/ReferData.vue";
import ApprovalStep from "@/components/business/ApprovalStep.vue";
import { addApplyGet, addApplyPost, uploadFile } from "@/request/api.js";
import Loading from "@/components/Loading.vue";
import Header from "@/components/Header.vue";
import { deepCopy } from "@/plugins/deepCopy.js";
import axios from "axios";
export default {
  name: "Application",
  data() {
    return {
      showHeader: this.$store.state.showHeader,
      showLoading: true,
      readList: {
        apply_title: "",
        cycle_status_desc: "",
        start_time: "",
        end_time: "",
        history_apply_num: "",
        cycle_long: ""
      },
      applyReason: "",
      ReferDataList: {
        rel_reg_num: "",
        open_app_num: "",
        tm_article_share_num: "",
        five_day_money: "",
        history_total_money: "",
        next_level_user_num: ""
      },
      stepList: [],
      activeStep: 0,
      staffer_id: "",
      fileList: [],
      imageList: [],
      uploadFilequery: {}
    };
  },
  components: {
    ReferData,
    ApprovalStep,
    Loading,
    Header
  },
  mounted() {
    this.staffer_id = localStorage.getItem("staffer_id");
    addApplyGet({ token: this.$store.state.token, id: this.staffer_id })
      .then(res => {
        // console.log(res)
        this.showLoading = false;
        if (res.code) {
            this.$dialog.alert({
                title:'提示',
                message: res.msg
            }).then(() => {
                this.$router.go(-1)
            });
        } else {
        let data = res.data;
        this.readList.apply_title = data.apply_title;
        this.readList.cycle_status_desc = data.cycle_status_desc;
        this.readList.start_time = data.start_time;
        this.readList.end_time = data.end_time;
        this.readList.history_apply_num = data.history_apply_num;
        this.readList.cycle_long = data.cycle_long;
        //参考数据
        this.ReferDataList.rel_reg_num = data.rel_reg_num;
        this.ReferDataList.open_app_num = data.open_app_num;
        this.ReferDataList.tm_article_share_num = data.tm_article_share_num;
        this.ReferDataList.five_day_money = data.five_day_money;
        this.ReferDataList.history_total_money = data.history_total_money;
        this.ReferDataList.next_level_user_num = data.next_level_user_num;
        //审批流
        this.stepList = data.checkLine;
        //获取图片上传阿里云凭证
        uploadFile({ token: this.$store.state.token })
          .then(res => {
            // console.log(res);
            this.uploadFilequery = res.data;
            // this.uploadFilequery.host =
            //   "https" + this.uploadFilequery.host.slice(4);
            if (this.isAndroid_ios()) {
              let up = document.getElementsByClassName("van-uploader__input");
              // console.log(up);
              up[0].setAttribute("capture", "camera");
            }
          })
          .catch(error => {
            console.log(error);
          });
        }
      })
      .catch(error => {
        console.log(error);
        this.showLoading = false;
      });
  },
  methods: {
    // 判断是安卓手机还是ios手机
    isAndroid_ios() {
      var u = navigator.userAgent,
        app = navigator.appVersion;
      // console.log(u)
      // console.log(app)
      var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //android终端或者uc浏览器
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      return isAndroid == true ? true : false;
    },
    //随机字符串
    random_string(len) {
      len = len || 32;
      var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      var maxPos = chars.length;
      var pwd = "";
      var i = 0;
      for (; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    submitApply() {
      this.showLoading = true;
      let lodash = require('lodash');
      let files = lodash.cloneDeep(this.fileList);
      for (let i = 0; i < files.length; i++) {
        let data = new FormData();
        const file = files[i];
        let ext = file.file.name.substr(file.file.name.lastIndexOf(".")).toLowerCase(); //获得后缀
        if (ext == ".png" || ext == ".jpeg" || ext == ".bmp" || ext == ".jpg"){
          let uploadFileName = this.uploadFilequery.dir + this.random_string()+ext;
          data.append("OSSAccessKeyId", this.uploadFilequery.accessid);
          data.append("policy", this.uploadFilequery.policy);
          data.append("Signature", this.uploadFilequery.signature);
          data.append("success_action_status", "200");
          data.append("key", uploadFileName);
          data.append("file", file.file);
          this.imageList.push(uploadFileName);
          axios
          .post(this.uploadFilequery.host, data, {
            headers: { "Content-Type": "application/x-www-form-urlencoded" }
          })
          .then(res => {
            // console.log('提交阿里云：' + res + '!');
            this.showLoading = false;
          })
          .catch(error => {
            console.log(error);
            this.showLoading = false;
          });
        }else {
          this.$toast({
            duration: 800,
            message: "图片格式不正确！"
          });
        }  
      }
      // console.log(this.imageList);
      addApplyPost({
        token: this.$store.state.token,
        id: this.staffer_id,
        remark: this.applyReason,
        apply_img: this.imageList
      })
        .then(res => {
          // console.log(res)
          this.showLoading = false;
          if (res.code == 0) {
            this.$toast({
              duration: 800,
              message: res.msg
            });
            const timer = setTimeout(() => {
              this.$router.push({ path: "/business" });
              clearInterval(timer);
            }, 1000);
          }else{
            this.$toast({
              duration: 800,
              message: res.code+':'+res.msg
            });
          }
        })
        .catch(error => {
          console.log(error.msg);
          this.showLoading = false;
        });
    }
  }
};
</script>
<style lang="less" scoped>
.apply {
  padding-bottom: 100px;
  .read_list {
    width: 100%;
    height: auto;
    background: #fff;
    li {
      padding: 10px 15px;
      line-height: 36px;
      border-bottom: 1px solid #f7f7f7;
      font-size: 14px;
      color: #999;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      label {
        flex: 1;
      }
      input {
        flex: 2;
        text-align: right;
        color: #151617;
        font-weight: bold;
      }
    }
  }
  .apply_reason,
  .upload_images {
    width: 100%;
    height: auto;
    background: #fff;
    margin-top: 10px;
    padding: 10px 15px;
    box-sizing: border-box;
    color: #151617;
    font-size: 14px;
    p {
      line-height: 36px;
      font-weight: bold;
    }
    .van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border: none;
    }
    .van-cell {
      padding: 0;
      font-size: 14px;
      color: #999;
    }
  }
  .upload_images {
    span {
      color: #999;
      font-weight: normal;
    }
    /deep/ .van-uploader__upload {
      background: #f7f7f7;
      .van-uploader__upload-icon {
        font-size: 30px;
      }
    }
    /deep/ .van-uploader__preview-delete {
      display: none;
    }
  }
  /deep/ .van-tabbar-item__text {
    display: block;
    width: 100%;
  }
  /deep/ .van-button--large {
    font-size: 16px;
    font-weight: bold;
    background-color: #02ccbd;
    color: #fff;
  }
}
</style>